<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="设备" prop="deviceId">
          <el-select
            v-model="queryParams.deviceId"
            placeholder="请选择设备"
            clearable
            filterable
            :loading="deviceLoading"
            style="width: 220px"
          >
            <el-option
              v-for="item in deviceOptions"
              :key="item.deviceId"
              :label="item.deviceName"
              :value="item.deviceId"
            >
              <div class="flex items-center">
                <span>{{ item.deviceName }}</span>
                <span class="text-gray-400 ml-2">({{ item.deviceId }})</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上报数据类型" prop="reportDataType">
          <el-select
            v-model="queryParams.reportDataType"
            placeholder="请选择上报数据类型"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="item in reportDataTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上报数据级别" prop="reportDataLevel">
          <el-select
            v-model="queryParams.reportDataLevel"
            placeholder="请选择上报数据级别"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="item in reportDataLevelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择处理状态"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="item in reportStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上传类型" prop="uploadType">
          <el-select
            v-model="queryParams.uploadType"
            placeholder="请选择上传类型"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="item in uploadTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上报数据时间" prop="reportDataTime">
          <el-date-picker
            v-model="queryParams.reportDataTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            style="width: 340px"
          />
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="queryParams.createTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            style="width: 340px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="warning" plain @click="handleExport">
            <Icon icon="ep:download" class="mr-5px" /> 导出
          </el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="list" border>
        <el-table-column label="设备名称" min-width="150">
          <template #default="{ row }">
            {{ getDeviceName(row.deviceId) }}
          </template>
        </el-table-column>
        <el-table-column label="设备ID" prop="deviceId" min-width="120" />
        <el-table-column label="上报数据类型" prop="reportDataType" min-width="120">
          <template #default="{ row }">
            {{ getReportDataTypeLabel(row.reportDataType) }}
          </template>
        </el-table-column>
        <el-table-column label="上报数据实际值" prop="reportDataValue" min-width="120" />
        <el-table-column label="上报数据级别" prop="reportDataLevel" min-width="120">
          <template #default="{ row }">
            <el-tag :type="getReportDataLevelType(row.reportDataLevel)">
              {{ getReportDataLevelLabel(row.reportDataLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="上报数据时间"
          prop="reportDataTime"
          min-width="150"
          :formatter="formatReportDataTime"
        />
        <el-table-column label="处理状态" prop="status" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getReportStatusType(row.status)">
              {{ getReportStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="上传类型" prop="uploadType" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getUploadTypeType(row.uploadType)">
              {{ getUploadTypeLabel(row.uploadType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="上报数据信息"
          prop="message"
          min-width="180"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="创建时间"
          prop="createTime"
          :formatter="dateFormatter"
          min-width="150"
        />
      </el-table>

      <Pagination
        v-if="total > 0"
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import * as ReportApi from '@/api/energy/report'
import * as DeviceApi from '@/api/energy/device'
import {
  ReportDataVO,
  reportDataTypeOptions,
  reportDataLevelOptions,
  reportStatusOptions,
  uploadTypeOptions,
  exportReportData
} from '@/api/energy/report'
import { DeviceVO } from '@/api/energy/device'
import { dateFormatter } from '@/utils/formatTime'
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import Pagination from '@/components/Pagination/index.vue'
import dayjs from 'dayjs'

// 列表数据
const list = ref<ReportDataVO[]>([])
const loading = ref(false)
const total = ref(0)

// 设备选择相关
const deviceOptions = ref<DeviceVO[]>([])
const deviceLoading = ref(false)
const loadDevices = async () => {
  deviceLoading.value = true
  try {
    const res = await DeviceApi.getDeviceList()
    deviceOptions.value = res || []
  } catch (error) {
    console.error('获取设备列表失败', error)
  } finally {
    deviceLoading.value = false
  }
}

// 查询条件
const queryFormRef = ref()
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceId: '',
  reportDataType: '',
  reportDataLevel: '',
  status: '',
  uploadType: undefined as number | undefined,
  uploadTypeExists: true,
  reportDataTime: [],
  createTime: []
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 确保查询参数中包含uploadType有值的条件
    const params = { ...queryParams }
    if (params.uploadType === undefined) {
      // 设置一个特殊参数，表示只查询uploadType有值的数据
      params.uploadTypeExists = true
    }

    const res = await ReportApi.getReportDataPage(params)
    if (res && res.list) {
      list.value = res.list
      total.value = res.total
    }
  } finally {
    loading.value = false
  }
}

// 获取设备名称
const getDeviceName = (deviceId: string) => {
  const device = deviceOptions.value.find((item) => item.deviceId === deviceId)
  return device ? device.deviceName : deviceId
}

// 工具方法
const getReportDataTypeLabel = (value: string) => {
  return reportDataTypeOptions.find((item) => item.value === value)?.label || value
}

const getReportDataLevelLabel = (value: string) => {
  return reportDataLevelOptions.find((item) => item.value === value)?.label || value
}

const getReportDataLevelType = (value: string) => {
  return reportDataLevelOptions.find((item) => item.value === value)?.type || ''
}

const getReportStatusLabel = (value: string) => {
  return reportStatusOptions.find((item) => item.value === value)?.label || value
}

const getReportStatusType = (value: string) => {
  return reportStatusOptions.find((item) => item.value === value)?.type || ''
}

const getUploadTypeLabel = (value: number) => {
  return uploadTypeOptions.find((item) => item.value === value)?.label || '未知'
}

const getUploadTypeType = (value: number) => {
  if (value === 1) return 'success'
  if (value === 2) return 'primary'
  return 'info'
}

// 查询操作
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 处理上报数据时间的格式化（特殊处理）
const formatReportDataTime = (_row: any, _column: any, cellValue: any): string => {
  try {
    // 处理空值或无效值
    if (cellValue === null || cellValue === undefined || cellValue === 0 || cellValue === '0') {
      return ''
    }

    // 检查是否是1970年的日期（无效日期）
    if (typeof cellValue === 'string' && cellValue.includes('1970')) {
      return ''
    }

    // 处理时间戳格式（数字）
    if (typeof cellValue === 'number') {
      // 时间戳为0或负数，视为无效
      if (cellValue <= 0) {
        return ''
      }

      // 确保是毫秒级时间戳
      const timestamp = cellValue.toString().length <= 10 ? cellValue * 1000 : cellValue
      return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
    }

    // 处理字符串时间格式
    if (typeof cellValue === 'string') {
      // 尝试解析字符串格式的时间戳
      if (/^\d+$/.test(cellValue)) {
        const timestamp = cellValue.length <= 10 ? parseInt(cellValue) * 1000 : parseInt(cellValue)
        return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
      }

      // 标准日期字符串
      return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
    }

    // 兜底使用通用格式化
    return dateFormatter(_row, _column, cellValue)
  } catch (error) {
    console.error('日期格式化错误', error, cellValue)
    return String(cellValue) || ''
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 显示导出进度
    ElMessage.success('正在导出能耗报告数据日志，请稍候...')
    // 执行导出
    const res = await exportReportData(queryParams)
    console.log('导出响应:', res) // 添加调试信息
  } catch (error: any) {
    console.error('导出错误:', error) // 添加错误详情日志
    ElMessage.error('导出失败: ' + error.message)
  }
}

// 页面加载时查询数据
onMounted(() => {
  loadDevices().then(() => {
    getList()
  })
})
</script>

<style scoped>
.json-preview {
  font-family: monospace;
  background-color: #f5f7fa;
}
</style>
